package com.sxj.PDMS.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class FileUtils {
    private static final String path = "D:\\user\\Desktop\\store\\";
    public static String upload(MultipartFile file){
        synchronized (FileUtils.class){
            //获取当前时间戳
            String flag = System.currentTimeMillis()+"";
            //获取文件名
            String fileName = file.getOriginalFilename();
            try {
               FileUtil.writeBytes(file.getBytes(),path+"\\"+flag+"-"+fileName);
                System.out.println(fileName+"上传成功");
                Thread.sleep(1L);
            } catch (Exception e) {
                System.out.println(fileName+"上传失败");
            }
            return flag;
        }
    }

    public static void downLoad(String flag, HttpServletResponse response){
        OutputStream outPutStream;
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name-> name.contains(flag)).findAny().orElse("");
        try{
            if(StrUtil.isNotEmpty(avatar)){
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(path+"\\"+avatar);
                outPutStream = response.getOutputStream();
                outPutStream.write(bytes);
                outPutStream.flush();
                outPutStream.close();
            }
        }catch (Exception e){
            System.out.println(avatar+"下载失败");
        }
    }
}
